<template>
  <van-dropdown-menu :direction="direction">
    <van-dropdown-item v-model="initValue" :options="list" />
  </van-dropdown-menu>
</template>

<script setup>
import { dicts, getDicts } from '@/store/dict.js';
import { ref, onMounted, watch } from 'vue';

const props = defineProps({
  value: { type: String, default: '' },
  propKey: { type: String, default: '' }, //  需要返回的字段
  propValue: { type: String, default: '' }, // 需要返回的值
  direction: { type: String, default: 'down' },
  dictName: { type: String, default: '' },
  dataList: { type: String, default: () => ([]) }
})

const emit = defineEmits(['update:value', 'change']);

const list = ref([]);
const initValue = ref(props.value || ''); //  记录初始化的值，同时这个值也是具有响应式的

watch(initValue, (newVal, oldVal) => {
  if (newVal !== oldVal) { //  避免死循环
    //  从数据中找到指定的数据 - 并将想要返回的字段进行返回
    console.log(initValue.value);
    emit('update:value', initValue.value);
    emit('change', initValue.value);
  }
})

watch(() => dicts.value[props.dictName], (newVal, oldVal) => {
  setResult(newVal);
})

//  加载数据 - 没必要在onMounted 里面完成
fetctDataList();

async function fetctDataList() {
  list.value = [];  //  减少缓存造成的不必要的麻烦

  if (props.dataList && props.dataList.length > 0) {
    setResult(props.dataList);
  } else {
    await getDicts([props.dictName])
  }
}


function setResult(data) {
  const _data = JSON.parse(JSON.stringify(data));

  list.value = _data.map(_s => {
    if (props.propKey) {
      _s.text = _s[props.propKey];
    }

    if (props.propValue) {
      _s.value = _s[props.propValue];
    }

    return _s;
  });
}
</script>

<style lang="scss" scoped></style>